package VerticalPrototypes;

import java.sql.*;

/**
 * @author Tyler
 */

//Class for adding an item to the global database.
public class AddItemToDatabase {
    
    //Instance of this class being used.
    private static AddItemToDatabase instance = null;
    
    public AddItemToDatabase()
    {
        Connection con = null;
        Statement st = null;
        ResultSet rs = null;

        //Hardcoded database location.
        String url = "snyamathi.dyndns.org:37965";
        String user = "root";
        String password = "baconatmidnight";
        
        //Hardcoded prototype item name, category, and ISBN.
        String item_name = "Hello World";
        String item_category = "Book";
        String item_isbn = "123-4-56-789012-3";

        try {
            //Connect to the databse.
            con = DriverManager.getConnection(url, user, password);
            st = con.createStatement();

            //Add passed item to database
            //See if the item exists first.
		//Tyler's manual SQL test string: SELECT * FROM items WHERE itemName = 'item1';
            if(!(rs == (st.executeQuery("SELECT * FROM items WHERE itemName = '" + item_name + "'"))))
            {   //Doesn't exist, add it.
		//Tyler's manual SQL test string: INSERT INTO items (itemName, itemCategory, itemISBN) VALUES ( 'item1', 'book', '1234567890123');
                rs = st.executeQuery("INSERT INTO items (itemName, itemCategory, itemISBN) VALUES ( '" + item_name + "', '" + item_category + "', '" + item_isbn + "')");
            }

            if (rs.next()) {
                System.out.println(rs.getString(1));
            }

        } catch (SQLException ex) {
                //Something happens.
        } finally {
            //Close connections safely - May not need to do this? Overkill?
            try {
                if (rs != null) {
                    rs.close();
                }
                if (st != null) {
                    st.close();
                }
                if (con != null) {
                    con.close();
                }

            } catch (SQLException ex) {
                    //Something happens.
            }
        }
    }
    
    //Execute the addition of item to global database.
    public static AddItemToDatabase user_AddItemToDatabase()
    {
        if(instance == null)
            instance = new AddItemToDatabase();
        return instance;
    }  
}